package com.xqboss.apps.service.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xqboss.apps.domain.user.UserWrenchDayCountRecord;
import com.xqboss.apps.domain.user.UserWrenchProductionRecord;
import com.xqboss.apps.mapper.user.UserWrenchDayCountRecordMapper;
import com.xqboss.apps.service.user.UserWrenchDayCountRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.xqboss.chain.domain.chain.dto.BaseRequest;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;

/**
 * <p>
 * 扳手每日产量记录表 定时任务0点更新 服务实现类
 * </p>
 *
 * @author 木鱼
 * @since 2024-01-16
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserWrenchDayCountRecordService extends ServiceImpl<UserWrenchDayCountRecordMapper, UserWrenchDayCountRecord> {
    @Autowired
    private UserWrenchProductionRecordService userWrenchProductionRecordService;

    public List<UserWrenchDayCountRecord> selectBasicList(BaseRequest request) {
        return baseMapper.selectList(Wrappers.<UserWrenchDayCountRecord>lambdaQuery());
    }

    public UserWrenchDayCountRecord selectByIdBasic(Long id) {
        return baseMapper.selectById(id);
    }

    public boolean saveBasic(UserWrenchDayCountRecord record) {
        return baseMapper.insert(record) > 0;
    }

    public boolean updateBasic(UserWrenchDayCountRecord record) {
        return baseMapper.updateById(record) > 0;
    }

    public boolean removeBasic(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    /**
     * 新增每日生产扳手数据 定时任务
     */
    public void wrenchProductionRecordDay() {
        // 查询所有用户
        List<UserWrenchProductionRecord> recordList = userWrenchProductionRecordService.list();
        if (recordList.size() == 0){
            return;
        }
        // 循环执行新增记录
        for (UserWrenchProductionRecord wrenchProductionRecord : recordList) {
            BigDecimal productionAmount = new BigDecimal(0);
            // 如果是已领取的状态且超过一天的则不计算
            if (wrenchProductionRecord.getEndTime() != null) {
                LocalDateTime endTime = wrenchProductionRecord.getEndTime().plusDays(1);
                if (ChronoUnit.DAYS.between( LocalDate.now(),endTime.toLocalDate()) >= 0) {
                    continue;
                }
            }
            // predictHour = 一共需要生产的小时数
            int predictHour = wrenchProductionRecord.getPredictDay() * 24;
            BigDecimal predictOutputWrench = wrenchProductionRecord.getPredictOutputWrench();
            // avgHourWrench = 平均每小时产出
            BigDecimal avgHourWrench = predictOutputWrench.divide(BigDecimal.valueOf(predictHour), 2, RoundingMode.HALF_UP);
            // avgDayWrench = 平均每天产出
            BigDecimal avgDayWrench = predictOutputWrench.divide(BigDecimal.valueOf(wrenchProductionRecord.getPredictDay()), 2, RoundingMode.HALF_UP);
            LocalDateTime startTime = wrenchProductionRecord.getStartTime();
            LocalDateTime today = LocalDateTime.now();
            // 不是是启动生产当天 才有生产收益, 如果是查看第一天或者最后一天收益则按小时计算
            Integer predictDay = wrenchProductionRecord.getPredictDay();
            // 结算完成的时间
            LocalDateTime plusDays = wrenchProductionRecord.getStartTime().toLocalDate().plusDays(predictDay + 1).atTime(0,0,0);
            // 距离24点相差的小时数
            LocalDateTime time = startTime.toLocalDate().plusDays(1).atTime(0, 0, 0);
            long hour = ChronoUnit.HOURS.between(startTime, time);
            if (plusDays.toLocalDate().equals(LocalDate.now())) {// 最后一天收益
                // 生产了多少小时
                long productionHour = 24L-hour;
                productionAmount = avgHourWrench.multiply(BigDecimal.valueOf(productionHour)).setScale(2, RoundingMode.HALF_UP);
            } else if (startTime.plusDays(1).toLocalDate().equals(LocalDate.now())) {//第一天收益
                // 已生产的小时
                productionAmount = avgHourWrench.multiply(BigDecimal.valueOf(hour)).setScale(2, RoundingMode.HALF_UP);
            } else if (!(startTime.toLocalDate().equals(today.toLocalDate())) && ChronoUnit.DAYS.between(plusDays.toLocalDate(), today.toLocalDate()) < 0) {// 非第一天也非最后一天收益
                productionAmount = avgDayWrench;
            }
            // 产出大于0才添加记录
            if (productionAmount.compareTo(BigDecimal.ZERO) > 0){
                UserWrenchDayCountRecord record = new UserWrenchDayCountRecord();
                record.setRecordId(wrenchProductionRecord.getId());
                record.setPermWrenchProductionId(wrenchProductionRecord.getPermWrenchProductionId());
                record.setUserId(wrenchProductionRecord.getUserId());
                record.setPredictOutputWrench(wrenchProductionRecord.getPredictOutputWrench());
                record.setTodayOutputWrench(productionAmount);
                record.setSaveTime(LocalDateTime.now());
                this.save(record);
            }

        }

    }
}